import React, { useState, useImperativeHandle, forwardRef } from 'react'
import { Button, Upload, MenuButton } from '@alifd/next'
import { getUGM } from '@/utils/handlePrimitive'
import { useMemoizedFn } from 'ahooks'
import { saveAs } from 'file-saver'
// import { getUGM } from '@/utils/handlePrimitive'
// import { isLayerExist } from '@/utils/tools'
import store from '@/store'
import { v4 as uuidv4 } from 'uuid'
import styles from './index.module.scss'
// import useRxdb from '@/components/Rxdb'
// import { rxdb } from 'rxdb/dist/types/plugins/key-compression'

const { Item } = MenuButton

const TopButtons = ({ handleButtonClick, getDataByUploadButton }, ref) => {
  // const rxdb = useRxdb()
  const [graphState, graphDispatchers] = store.useModel('graph')
  const { ugmId, data, bim } = graphState

  const ghostButtons = ['手动规划', '手动规划(新)', '切换房间显示', '切换站点显示', '切换门显示', '切换窗显示']
  const visibleButtons = ['切换房间显示', '切换站点显示', '切换门显示', '切换窗显示']
  const loadButtons = ['上传图纸']
  const saveButtons = ['保存图纸']
  const handlerButtons = ['自动补线']
  const [buttonState, setButtonState] = useState({
    居中: false,
    上传图纸: false,
    保存图纸: false,
    自动补线: false,
    清空图纸: false,
    自动规划: false,
    手动规划: false,
    合并房间: false,
    // '自动规划(新)': false,
    // '手动规划(新)': false,
    // '划分户型(新)': false,
    切换房间显示: true,
    切换站点显示: true,
    切换门显示: true,
    切换窗显示: true,
    户型标准: false,
    站点检查: false
  })
  const [buttonLoading, setButtonLoading] = useState({
    自动规划: false,
    手动规划: false,
    合并房间: false
    // '自动规划(新)': false,
    // '手动规划(新)': false,
    // '划分户型(新)': false
  })

  const [architectureFile, setArchitectureFile] = useState()
  const [structureFile, setStructureFile] = useState()
  const [ugmFile, setUgmFile] = useState()

  const getGraphType = useMemoizedFn(({ elements, data, bim }) => {
    if (data && bim) return 'ugm'
    const beamLayer = elements.nodes.find(i => i.data && i.data.definition === 'Layer' && i.data.name === 'Beam')
    const beamLineArr = elements.nodes.filter(
      i => i.data && i.data.definition === 'Line' && i.data.layer === beamLayer.data.id
    )
    return beamLineArr.length === 0 ? 'architecture' : 'structure'
  })

  const createLoadButton = useMemoizedFn(() => {
    const getKey = () => {
      if (!architectureFile && !structureFile) {
        return '上传图纸'
      } else if (!architectureFile && structureFile) {
        return '请上传建筑图'
      } else if (architectureFile && !structureFile) {
        return '请上传结构图'
      }
    }
    if (ugmFile || architectureFile || structureFile) {
      return (
        <Button
          key={'载入图纸'}
          className={styles.button}
          ghost="dark"
          type="normal"
          text
          onClick={() => {
            getDataByUploadButton({ architecture: architectureFile, structure: structureFile, ugm: ugmFile })
            setArchitectureFile(undefined)
            setStructureFile(undefined)
            setUgmFile(undefined)
          }}
        >
          载入图纸
        </Button>
      )
    } else {
      return (
        <Upload
          key={getKey()}
          beforeUpload={file => {
            const reader = new FileReader()
            reader.readAsText(file)
            reader.onload = function () {
              const data = JSON.parse(reader.result)
              if (window.isDev) console.log('base64形式的pdf', data)
              const type = getGraphType(data)
              if (type === 'ugm') {
                setUgmFile(data)
                graphDispatchers.saveData({ data, type: 'ugm', ugmId: ugmId })
              } else if (type === 'structure') {
                setStructureFile(data)
                graphDispatchers.saveData({ data, type: 'structure', ugmId: ugmId })
              } else if (type === 'architecture') {
                setArchitectureFile(data)
                graphDispatchers.saveData({ data, type: 'architecture', ugmId: ugmId })
              }
            }
            reader.onerror = function () {
              console.error('读取pdf出错')
            }
          }}
          accept={'.json'}
          multiple
          limit={2}
          disabled={data && data.cols && data.cols.point.length > 0}
          request={() => {}}
        >
          <Button className={styles.button} ghost="dark" type="normal" text>
            {getKey()}
          </Button>
        </Upload>
      )
    }
  })

  const addCurrentTimeToUGM = ugm => {
    if (ugm.current_time) return ugm
    if (!ugm.data.cols.timestamp || !ugm.data.cols.timestamp.length) {
      const timestamp = { id: uuidv4(), timestamp: Date.now().toString(), definition: 'timestamp' }
      ugm.data.cols.timestamp = [timestamp]
      ugm.data.docs[timestamp.id] = timestamp
      ugm.current_time = timestamp.timestamp
    } else {
      ugm.current_time = ugm.timestamp[0].timestamp
    }
    return ugm
  }

  const createSaveButton = useMemoizedFn(key => {
    return (
      <Button
        className={styles.button}
        ghost="dark"
        type="normal"
        text
        key={key}
        disabled={!(data && data.cols && data.cols.point.length > 0)}
        onClick={async () => {
          const ugm = addCurrentTimeToUGM(getUGM({ data: data, bim: bim }))
          const blob = new Blob([JSON.stringify(ugm)], { type: 'text/plain;charset=utf-8' })
          saveAs(blob, `${ugmId}.json`)
        }}
      >
        {key}
      </Button>
    )
  })

  const createDoorLineButton = useMemoizedFn(key => {
    return (
      <Button
        className={styles.button}
        ghost="dark"
        type="normal"
        text
        key={key}
        disabled={!(data && data.cols && data.cols.point.length > 0)}
        onClick={async () => {
          const newLines = []
          const doorLayerId = data.cols.layer.find(i => i.type === 'Door').id
          const doorArcs = data.cols.arc.filter(i => i.layer === doorLayerId)
          for (const i in doorArcs) {
            const a_arc = doorArcs[i]
            const points = [a_arc.start_point, a_arc.end_point]
            for (const j in points) {
              const a_point = points[j]
              const newLineId = uuidv4()
              const nLine = {
                material: doorArcs[0].material,
                id: newLineId,
                layer: doorLayerId,
                definition: 'line',
                start: a_arc.center,
                end: a_point,
                name: newLineId,
                value: newLineId
              }
              newLines.push(nLine)
            }
          }
          // console.log(newLines)
          // const timestamp = { id: data.cols.timestamp.find(i => i.definition === 'timestamp').id, timestamp: Date.now().toString(), definition: 'timestamp' }
          // rxdb.changeDocs({addData: newLines, updateData: [timestamp], deleteData: []})
        }}
      >
        {key}
      </Button>
    )
  })

  const createTopButtons = useMemoizedFn(() => {
    const keys = Object.keys(buttonState)
    const buttons = []
    const menu = []
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      if (loadButtons.includes(key)) {
        buttons.push(createLoadButton(key))
      } else if (saveButtons.includes(key)) {
        buttons.push(createSaveButton(key))
      } else if (handlerButtons.includes(key)) {
        buttons.push(createDoorLineButton(key))
      } else {
        if (visibleButtons.includes(key)) {
          menu.push(<Item key={key}>{key}</Item>)
        } else {
          buttons.push(
            <Button
              className={styles.button}
              key={key}
              loading={buttonLoading[key]}
              ghost={ghostButtons.includes(key) && buttonState[key] ? 'light' : 'dark'}
              disabled={(key === '自动规划' || key === '合并房间') && ugmId.includes('_')}
              type="normal"
              text
              onClick={e => {
                handleButtonClick({ e, bool: !buttonState[key] })
                setButtonState({ ...buttonState, [key]: !buttonState[key] })
              }}
            >
              {key}
            </Button>
          )
        }
      }
    }
    buttons.push(
      <MenuButton
        key={'MenuButton'}
        className={styles.MenuButton}
        label="切换显示"
        ghost="dark"
        type="normal"
        text
        onItemClick={(key, item, e) => {
          handleButtonClick({ e, bool: !buttonState[key] })
          setButtonState({ ...buttonState, [key]: !buttonState[key] })
        }}
      >
        {menu}
      </MenuButton>
    )

    return buttons
  })

  useImperativeHandle(ref, () => ({
    setButtonLoading: arg => setButtonLoading({ ...buttonLoading, ...arg })
  }))

  return <div className={styles.TopButtons}>{createTopButtons()}</div>
}

export default forwardRef(TopButtons)
